package com.meixiaoliang.portal.core.rongyun.impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.meixiaoliang.portal.core.exception.BusinessException;
import com.meixiaoliang.portal.core.rongyun.RongyunService;
import com.meixiaoliang.portal.core.util.AssertUtil;

import io.rong.RongCloud;
import io.rong.methods.user.User;
import io.rong.models.response.TokenResult;
import io.rong.models.user.UserModel;

@Component
public class RongyunServiceImpl implements RongyunService {

    @Value("${rongyun.appKey}")
    public String appKey;

    @Value("${rongyun.appSecret}")
    public String appSecret;

    @Override
    public String getToken(String userId, String userName) {

        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
        User user = rongCloud.user;

        /**
         * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/user/user.html#register
         *
         * 注册用户，生成用户在融云的唯一身份标识 Token
         */
        UserModel userModel = new UserModel().setId(userId).setName(userName).setPortrait("http://www.rongcloud.cn/images/logo.png");
        TokenResult result = null;
        try {
            result = user.register(userModel);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("融云注册用户失败");
        }

        AssertUtil.isTrue(result.getCode() == 200, "融云注册用户失败");

        return result.getToken();
    }
}
